<?php namespace App\Models;

use \System\Model;

class Users extends Model
{
    protected $table = "users";
    protected $id = 'id';
    protected $fields = ['id', 'username', 'password', 'email', 'avatar', 'group', 'zone', 'deleted'];
    private $session;

    public function __construct()
    {
        parent::__construct();
        $this->session = new \System\Session();
    }

    public function login($username, $password, $expire)
    {
        $crypt = new \System\Crypt();
        $user = $this->where('username', $username)->first();

        if (!$user) {
            $this->error = "Not Find Username";
        } elseif ($user['password'] != $crypt->md5($password)) {
            $this->error = 'Password is error';
        } else {
            $group = $this->db->query('SELECT * FROM groups WHERE id=' . $user['group'])->first();
            $user['group'] = $group;
            $this->session->register($expire);
            $this->session->set('user', $user);
            $this->session->set('login', true);
            $this->session->set('remember', ($expire > 7200) ? true : false);
        }
    }

    public function logout()
    {
        $this->session->end();
        setcookie('FISHSESSID', '');
    }

    public function checkLogin()
    {
        if ($this->session->get('remember')) {
            $this->session->renew();
        }
        return ($this->session->user && $this->session->login) ? $this->session->user : null;
    }

    public function findUser($string,$type="name") {
        switch ($type) {
            case 0:
            case "name":
            default:
                $this->where("username",$string);
                break;
            case 1:
            case "email":
                $this->where("mail",$string);
                break;
        }
        return $this->first();
    }
}